<template>
  <div style="width:100%;">
    <div style="display: flex; align-items: center; margin-bottom: 10px;">
      <el-input style="width: 200px; margin: 5px 5px " placeholder="查询订单编号"  v-model="orderId" ></el-input>
      <el-select style="width: 200px; margin: 5px 5px" v-model="state" placeholder="查询订单状态" clearable>
        <el-option
          v-for="item in states"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" @click="pageList(1)">查询</el-button>
      <el-button type="default" @click="reset" style="margin-left: 10px;">重置</el-button>
    </div>
    <el-table :data="tableData" stripe align="center" style="line-height: 30px;margin-top: 20px;">
      <el-table-column prop="_id" label="订单编号" align="center" width="320px"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180px" align="center">
        <template v-slot="scope">
          <span>{{ scope.row.createdAt ? new Date(scope.row.createdAt).toLocaleString() : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户账号" width="180px" align="center"></el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="180px" align="center">
        <template v-slot="scope">
          <span>￥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100px" align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status==='待支付'" type="warning">待支付</el-tag>
          <el-tag v-else-if="scope.row.status==='待发货'" type="primary">待发货</el-tag>
          <el-tag v-else-if="scope.row.status==='待收货'" type="primary">待收货</el-tag>
          <el-tag v-else-if="scope.row.status==='待评价'" type="primary">待评价</el-tag>
          <el-tag v-else-if="scope.row.status==='已完成'" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status==='已取消'" type="warning">已取消</el-tag>
          <el-tag v-else-if="scope.row.status==='退款审核中'" type="danger">退款审核中</el-tag>
          <el-tag v-else-if="scope.row.status==='退款完成'" type="success">退款完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" @click="openOrderDetail(scope.row)">查看详情</el-button>
          <el-button v-if="scope.row.status==='待发货'" type="primary" @click="openShipDialog(scope.row)">发货</el-button>
          <el-button v-if="scope.row.status==='待发货'" type="danger" @click="openCancelDialog(scope.row)">取消订单</el-button>
          <el-button v-if="scope.row.status==='退款审核中'" type="warning" @click="openRefundDialog(scope.row)">处理退款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-style" :style="paginationStyle">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>

  <!--编辑-->
  <el-dialog title="订单管理" v-model="fromVisible" width="800px">
  <el-form :model="updateList" label-width="80px" style="padding-right: 20px">
    <el-form-item label="订单编号">
      <el-input v-model="updateList.orderId" placeholder="订单编号" disabled></el-input>
    </el-form-item>
    <el-form-item label="订单状态">
      <div class="mb-2 flex items-center text-sm">
        <el-radio-group v-model="orderState">

          <el-radio v-if="updateList.state==0" disabled :value=0 label=0>待支付</el-radio>
          <el-radio v-if="updateList.state==1 || updateList.state==2" :disabled="updateList.state==2" :value=2 label=0>已发货</el-radio>
          <el-radio v-if="updateList.state==3" :value=3 label=3 disabled>待评价</el-radio>
          <el-radio v-if="updateList.state==4" :value=4 label=4 disabled>已完成</el-radio>
          <el-radio v-if="updateList.state==-1" :value=-1 label=-1 disabled>已取消</el-radio>
          <el-radio v-if="updateList.state==-2" :value=-2 label=1 disabled>退款申请中</el-radio>
          <el-radio v-if="updateList.state==-3" :value=-3 label=1 disabled>退款完成</el-radio>
          
        </el-radio-group>
      </div>
    </el-form-item>
  
    <div v-if="updateList.state===-2"> 
    <el-form-item label="退款理由">
      <el-input v-model="updateList.reason" placeholder="退款理由" disabled type="textarea" :rows="3"></el-input>
    </el-form-item>
    <el-form-item label="审核">
      <div class="mb-2 flex items-center text-sm">
        <el-radio-group v-model="editOrderState">
          <el-radio :value=0 label=0>通过</el-radio>
          <el-radio :value=1 label=1>不通过</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    </div>

  </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="fromVisible= false">取 消</el-button>
        <el-button type="primary" v-if="updateList.state==1||updateList.state==-2" @click="Edit">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!--查看订单商品详情-->
  <el-dialog title="订单商品详情" v-model="detailsVisible" width="1200px">
    <el-table :data="itemList" style="width: 100%">
    <el-table-column prop="goodsId" label="商品编号" align="center"></el-table-column>
    <el-table-column label="商品封面" width="120" align="center">
        <template v-slot="scope">
          <div style="display: flex; align-items: center">
            <el-image style="width: 100px; height: 100px; border-radius: 50%"
              :src="scope.row.pic ? 
              url + scope.row.pic
              : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              :preview-src-list="[url + scope.row.pic]" :preview-teleported="true"
            ></el-image>
          </div>
        </template>
      </el-table-column>
    <el-table-column prop="goodsName" label="商品名称" width="180px" align="center"></el-table-column>
    <el-table-column prop="number" label="购买数量" width="180px" align="center"></el-table-column>
    <el-table-column prop="goodsType" label="商品类型" width="180px" align="center"></el-table-column>
    <el-table-column prop="price" label="金额" width="180px" align="center"></el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="180px" align="center"></el-table-column>
  </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="detailsVisible= false">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 退款处理对话框 -->
  <el-dialog title="处理退款" v-model="refundVisible" width="500px">
    <el-form :model="refundForm" label-width="80px">
      <el-form-item label="退款理由">
        <el-input v-model="refundForm.reason" type="textarea" :rows="3" disabled></el-input>
      </el-form-item>
      <el-form-item label="处理结果">
        <el-radio-group v-model="refundForm.result">
          <el-radio :label="0">通过</el-radio>
          <el-radio :label="1">拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="处理意见">
        <el-input v-model="refundForm.comment" type="textarea" :rows="3" placeholder="请输入处理意见"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="refundVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRefund">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 评价查看对话框 -->
  <el-dialog title="订单评价" v-model="evaluationVisible" width="800px">
    <el-table :data="evaluationList" stripe>
      <el-table-column prop="bookName" label="商品名称" width="180px"></el-table-column>
      <el-table-column prop="rating" label="评分" width="100px">
        <template v-slot="scope">
          <el-rate v-model="scope.row.rating" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="评价内容"></el-table-column>
      <el-table-column prop="createTime" label="评价时间" width="180px"></el-table-column>
    </el-table>
  </el-dialog>

  <!-- 退款审核弹窗 -->
  <el-dialog v-model="refundDialogVisible" title="退款审核">
    <el-form>
      <el-form-item label="退款理由">
        <el-input v-model="refundDialogData.reason" disabled />
      </el-form-item>
      <el-form-item label="审核结果">
        <el-radio-group v-model="refundDialogData.approve">
          <el-radio :label="true">通过</el-radio>
          <el-radio :label="false">拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="处理意见">
        <el-input v-model="refundDialogData.adminComment" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="refundDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRefundDialog">确定</el-button>
    </template>
  </el-dialog>

  <!-- 强制状态修改弹窗 -->
  <el-dialog v-model="forceStatusDialogVisible" title="强制修改订单状态">
    <el-form>
      <el-form-item label="新状态">
        <el-select v-model="forceStatusData.newStatus" placeholder="请选择新状态">
          <el-option label="待支付" value="待支付" />
          <el-option label="待发货" value="待发货" />
          <el-option label="待收货" value="待收货" />
          <el-option label="待评价" value="待评价" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已取消" value="已取消" />
          <el-option label="退款审核中" value="退款审核中" />
          <el-option label="退款完成" value="退款完成" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="forceStatusData.adminComment" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="forceStatusDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForceStatusDialog">确定</el-button>
    </template>
  </el-dialog>

  <!-- 订单详情弹窗 -->
  <el-dialog v-model="orderDetailVisible" title="订单详情">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="订单编号">{{ orderDetail._id }}</el-descriptions-item>
      <el-descriptions-item label="用户ID">{{ orderDetail.userId }}</el-descriptions-item>
      <el-descriptions-item label="状态">{{ orderDetail.status }}</el-descriptions-item>
      <el-descriptions-item label="总金额">￥{{ orderDetail.totalAmount }}</el-descriptions-item>
      <el-descriptions-item label="收货人">{{ orderDetail.address?.receiverName }}</el-descriptions-item>
      <el-descriptions-item label="收货电话">{{ orderDetail.address?.receiverPhone }}</el-descriptions-item>
      <el-descriptions-item label="收货地址">{{ orderDetail.address?.fullAddress }}</el-descriptions-item>
      <el-descriptions-item label="商品明细">
        <el-table :data="orderDetail.items" size="small">
          <el-table-column prop="name" label="商品名"/>
          <el-table-column prop="quantity" label="数量"/>
          <el-table-column prop="price" label="单价"/>
        </el-table>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="orderDetailVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 取消订单对话框 -->
  <el-dialog v-model="cancelDialogVisible" title="取消订单">
    <el-form>
      <el-form-item label="取消理由">
        <el-input v-model="cancelDialogData.reason" type="textarea" :rows="3" placeholder="请输入取消理由" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitCancelDialog">确定</el-button>
    </template>
  </el-dialog>

  <!-- 发货对话框 -->
  <el-dialog v-model="shipDialogVisible" title="订单发货">
    <el-form>
      <el-form-item label="物流公司">
        <el-select v-model="shipDialogData.logisticsCompany" placeholder="请选择物流公司">
          <el-option
            v-for="item in logisticsCompanies"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号">
        <el-input v-model="shipDialogData.trackingNumber" placeholder="请输入物流单号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="shipDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitShipDialog">确定</el-button>
    </template>
  </el-dialog>

</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { page, update, searchDetails, handleRefund as apiHandleRefund, getEvaluations, getAllOrders, processRefund, forceUpdateStatus, shipOrder } from '@/api/order'
import { ElMessage } from 'element-plus';

const url = 'http://localhost:8088/petstores/download/'
const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const orderId = ref("");
const orderState = ref(0)
const states = ref([
  { value: 0, label: '待支付' },
  { value: 1, label: '待发货' },
  { value: 2, label: '待收货' },
  { value: 3, label: '待评价' },
  { value: 4, label: '已完成' },
  { value: -1, label: '已取消' },
  { value: -2, label: '退款申请中' },
  { value: -3, label: '退款完成' },
]);
const state = ref(null);
const editOrderState = ref(-1);
const lock = ref(false);
const oldScroll = ref(0);
const paginationStyle = ref({position:'fixed'})

// 退款处理
const refundVisible = ref(false);
const refundForm = ref({
  orderId: '',
  reason: '',
  result: 0,
  comment: ''
});

const showRefundDialog = (row) => {
  refundForm.value = {
    orderId: row.orderId,
    reason: row.reason,
    result: 0,
    comment: ''
  };
  refundVisible.value = true;
};

const submitRefund = async () => {
  try {
    const result = await apiHandleRefund({
      orderId: refundForm.value.orderId,
      result: refundForm.value.result,
      comment: refundForm.value.comment
    });
    
    if (result.data.statusCode === "200") {
      ElMessage.success("处理成功");
      refundVisible.value = false;
      pageList(1);
    } else {
      ElMessage.error(result.data.message);
    }
  } catch (error) {
    ElMessage.error("处理失败");
  }
};

// 评价查看
const evaluationVisible = ref(false);
const evaluationList = ref([]);

const handleEvaluation = async (row) => {
  try {
    const result = await getEvaluations(row.orderId);
    if (result.data.statusCode === "200") {
      evaluationList.value = result.data.data;
      evaluationVisible.value = true;
    } else {
      ElMessage.error(result.data.message);
    }
  } catch (error) {
    ElMessage.error("获取评价失败");
  }
};

const reset = () => {
  orderId.value = '';
  state.value = null;
  pageList(1);
};
const pageList = (pageNumVal) => {
  pageNum.value = pageNumVal || pageNum.value;
  let statusValue = null;
  if (state.value !== null && state.value !== undefined && state.value !== '') {
    // 状态值转为后端实际状态
    const statusMap = {
      0: '待支付',
      1: '待发货',
      2: '待收货',
      3: '待评价',
      4: '已完成',
      '-1': '已取消',
      '-2': '退款审核中',
      '-3': '退款完成'
    };
    statusValue = statusMap[state.value];
  }
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    orderId: orderId.value,
    state: statusValue
  };
  getAllOrders(params).then(resp => {
    console.log('订单数据响应:', resp);
    if (resp.data && resp.data.data) {
      tableData.value = resp.data.data.records || [];
      total.value = resp.data.data.total || 0;
    } else {
      ElMessage.warning('获取订单数据失败');
      tableData.value = [];
      total.value = 0;
    }
  }).catch(e => {
    console.error('获取订单数据错误:', e);
    ElMessage.error('获取订单数据失败: ' + (e.message || '未知错误'));
    tableData.value = [];
    total.value = 0;
  });
};

onMounted(() => {
  pageList();
  scrollListener();
});

const handleCurrentChange = (pageNum) => {
  pageList(pageNum);
};

const handleSizeChange = (pageSizeVal) => {
  pageSize.value = pageSizeVal;
  pageList();
};

const scrollListener = () => {
  const scrollableElement = document.getElementById('el-main');

// 监听滚动事件
scrollableElement.addEventListener('scroll', () => {
    checkIfBottomReached(scrollableElement);
});

function checkIfBottomReached(element) {
    // 获取元素的滚动高度和可视区域高度
    const elementHeight = element.clientHeight;
    const totalHeight = element.scrollHeight;
  const scrollTop = element.scrollTop;
    const direction = scrollTop - oldScroll.value
  console.log(elementHeight, totalHeight, scrollTop);
    // 判断是否滚动到底部
  if (scrollTop + elementHeight >= totalHeight-10) {
    paginationStyle.value = {
    }
    lock.value = true;
  } else {
    if (lock.value == false||direction<0) {
      paginationStyle.value = {
        position:'fixed',
      }
    }
  }
  oldScroll.value = scrollTop;
}
}

//编辑
const updateList=ref({})
const fromVisible=ref(false)
const handleEdit = (row) => {
  console.log(row, '编辑');
  if(row.state===1||row.state===-2)
  {
    switch (updateList.value.state) {
    case -3:
      orderState.value = -3;
      break;
    case -2:
      orderState.value = -2;
      break;
    case -1:
      orderState.value = -1;
      break;
    case 0:
      orderState.value = 0;
      break;
    case 2:
      orderState.value = 2;
      break;
    case 3:
      orderState.value = 3;
      break;
    case 4:
      orderState.value = 4;
      break;

  }
    updateList.value = JSON.parse(JSON.stringify(row));//当前订单
    fromVisible.value = true;
  }
  else{
    ElMessage.warning("暂无编辑权限!")
  }

};
const Edit = () => {// 保存按钮触发更新
  if (editOrderState.value == 0 && updateList.value.state == -2) {
    updateList.value.state = -3;
  } else if (editOrderState.value == 1 && updateList.value.state == -2){
    updateList.value.state = -22;//审核不通过
  } else if(updateList.value.state==1){
    updateList.value.state = orderState.value;
  }
  update(updateList.value).then(resp => {
    var result=resp.data
    if (result.statusCode === "200") {
      pageList(1)
      fromVisible.value = false
      ElMessage.success("修改成功!")
      editOrderState.value=-1;
    }
    else {
      ElMessage.error(result.message)
    }
  })
  .catch(error=>{
    ElMessage.error(error)
  })
}

//查看详情
const itemList=ref([])
const detailsVisible=ref(false)
const handelDetails = (row) => {
  searchDetails(row.orderId).then(resp => {
    console.log('订单详情响应:', resp); // 添加日志
    if (resp.data && resp.data.data) {
      itemList.value = resp.data.data;
      detailsVisible.value = true;
    } else {
      ElMessage.warning('获取订单详情失败');
    }
  }).catch(e => {
    console.error('获取订单详情错误:', e);
    ElMessage.error('获取订单详情失败: ' + (e.message || '未知错误'));
  });
};

//取消
const handleCancel=()=>{
  fromVisible.value= false;
  editOrderState.value=-1;
}

const refundDialogVisible = ref(false);
const refundDialogData = ref({});
const openRefundDialog = (row) => {
  refundDialogData.value = {
    ...row,
    approve: true, // 默认选中"通过"
    adminComment: '',
    reason: row.refundInfo?.reason || ''
  };
  refundDialogVisible.value = true;
};
const submitRefundDialog = async () => {
  try {
    await processRefund({
      orderId: refundDialogData.value._id,
      approve: refundDialogData.value.approve,
      adminComment: refundDialogData.value.adminComment
    });
    ElMessage.success('处理成功');
    refundDialogVisible.value = false;
    pageList(1);
  } catch (e) {
    ElMessage.error('处理失败');
  }
};

const forceStatusDialogVisible = ref(false);
const forceStatusData = ref({});
const openForceStatusDialog = (row) => {
  forceStatusData.value = { ...row, newStatus: '', adminComment: '' };
  forceStatusDialogVisible.value = true;
};
const submitForceStatusDialog = async () => {
  try {
    await forceUpdateStatus({
      orderId: forceStatusData.value._id,
      status: forceStatusData.value.newStatus,
      adminComment: forceStatusData.value.adminComment
    });
    ElMessage.success('修改成功');
    forceStatusDialogVisible.value = false;
    pageList(1);
  } catch (e) {
    ElMessage.error('修改失败');
  }
};

const orderDetailVisible = ref(false);
const orderDetail = ref({});
const openOrderDetail = (row) => {
  orderDetail.value = row;
  orderDetailVisible.value = true;
};

const handleShip = async (row) => {
  try {
    await shipOrder({ orderId: row._id });
    ElMessage.success('发货成功');
    pageList(1);
  } catch (e) {
    ElMessage.error('发货失败');
  }
};

// 取消订单
const cancelDialogVisible = ref(false);
const cancelDialogData = ref({});

const openCancelDialog = (row) => {
  cancelDialogData.value = {
    orderId: row._id,
    reason: ''
  };
  cancelDialogVisible.value = true;
};

const submitCancelDialog = async () => {
  try {
    await forceUpdateStatus({
      orderId: cancelDialogData.value.orderId,
      status: '已取消',
      adminComment: cancelDialogData.value.reason
    });
    ElMessage.success('订单已取消');
    cancelDialogVisible.value = false;
    pageList(1);
  } catch (e) {
    ElMessage.error('取消订单失败');
  }
};

// 物流公司选项
const logisticsCompanies = ref([
  { value: 'SF', label: '顺丰速运' },
  { value: 'YTO', label: '圆通速递' },
  { value: 'ZTO', label: '中通快递' },
  { value: 'STO', label: '申通快递' },
  { value: 'YUNDA', label: '韵达快递' },
  { value: 'EMS', label: 'EMS' },
  { value: 'JD', label: '京东物流' },
  { value: 'DBL', label: '德邦物流' }
]);

// 发货对话框
const shipDialogVisible = ref(false);
const shipDialogData = ref({
  orderId: '',
  logisticsCompany: '',
  trackingNumber: ''
});

const openShipDialog = (row) => {
  shipDialogData.value = {
    orderId: row._id,
    logisticsCompany: '',
    trackingNumber: ''
  };
  shipDialogVisible.value = true;
};

const submitShipDialog = async () => {
  if (!shipDialogData.value.logisticsCompany) {
    ElMessage.warning('请选择物流公司');
    return;
  }
  if (!shipDialogData.value.trackingNumber) {
    ElMessage.warning('请输入物流单号');
    return;
  }
  
  try {
    await shipOrder({
      orderId: shipDialogData.value.orderId,
      logisticsCompany: shipDialogData.value.logisticsCompany,
      trackingNumber: shipDialogData.value.trackingNumber
    });
    ElMessage.success('发货成功');
    shipDialogVisible.value = false;
    pageList(1);
  } catch (e) {
    ElMessage.error('发货失败');
  }
};

</script>

<style lang="scss" scoped>
.el-table {
  line-height: 30px;
}
.el-table .el-table__body-wrapper tbody tr {
  height: 20px;
}
.pagination-style {
  bottom: 0;
  width: 100%;
  padding: 10px 0;
  z-index: 1;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-style .el-pagination {
  padding: 2px 10px;
}
</style>